import {Injectable} from '@angular/core';
import {Response, RequestOptionsArgs, RequestMethod, Request, Headers} from '@angular/http';
import {Router} from "@angular/router";
import {NzMessageService} from "ng-zorro-antd";
import {HttpClient} from "@angular/common/http";
import {Observable, Subject} from "rxjs/index";
import {BlockUiService} from "./block-ui.service";

@Injectable()
export class HttpService {

  public subject: Subject<boolean> = new Subject<boolean>()

  public domain = 'http://47.97.212.129:3501'
  // public domain = ''
  private token = ''


  constructor(public http: HttpClient,
              private router: Router,
              public block:BlockUiService,
              private message: NzMessageService) {
  }

//给微信用户(Observable)关注提供的方法
  public get currentUser(): Observable<boolean> {
    return this.subject.asObservable();
  }

  getRequestOptionsArgs() {
    let header = new Headers();
    header.append('X-Requested-With', 'XMLHttpRequest');
    let option = {headers: header};
    return option;
  }

  /*
    get
   */
  async get(url: string, options?) {
    if (!options) options = {params: {ts: new Date().getTime()}};

    Object.assign(options, this.getRequestOptionsArgs());

   this.block.blockUI()

    const result = await this.http.get(this.domain + url, options).toPromise().then((res: any) => {

      return this.HandSuccessResult(res);
    }).catch(async res => {

      await this.HandErrorResult(res);
    });
    return result;
  }

  /**
   * http post重写
   */
  async post(url: string, body?: any, option?) {
    if (!option) option = {};
    Object.assign(option, this.getRequestOptionsArgs());
    this.block.blockUI()
    const result = await this.http.post(this.domain + url, body, option).toPromise().then((res: any) => {
      return this.HandSuccessResult(res);
    }).catch(async res => {
      await this.HandErrorResult(res);
    });
    return result;
  }

  /**
   * 处理http正确返回结果
   */
  HandSuccessResult(res: any) {
    let httpresult = res;
    if (httpresult.result) {
     this.block.UnBlockUI()
      if (httpresult.data) {
        return httpresult.data;
      } else {
        return true;
      }
    }
    else {
      // this.mydialog.openMessage(httpresult.message, "操作失败", "error");
      throw res;
    }
  }

  /**
   * 处理http错误正确返回结果
   */
  async HandErrorResult(res: any) {
    if (res.status == 401) {
      await this.router.navigateByUrl('login');
      throw res;
    }
    this.block.UnBlockUI();
    if (res.ok) {
      let result = res;
      this.message.error(result.message || '抱歉,无任何错误信息返回!')
    }
    else {
      if (res.status == 403) {
        this.message.error('您没有访问权限!');
      }
      else if (res.status < 200 || res.status > 290) {
        this.message.error(res.statusText || '网络异常!');
      }
    }
    throw res;
  }
}
